# -*- coding: utf-8 -*-

#    Copyright (C) 2005-2014 by Promotux
#                        di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of Promogest.

#    Promogest is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    Promogest is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with Promogest.  If not, see <http://www.gnu.org/licenses/>.

import datetime
from web_lib.page import Page
from web_lib.webutils import Response, expose , json , salvaInSessione, leggiInSessione , permalinkaTitle
import Environment
from web_lib.session import Session as S
from lib.utils import prep2json
from webEnv import *



@expose('/pg/news_detail/<permalink>')
def newsDetail(req,subdomain=None, permalink=None):
    from dao.News import News
    news = News(req=req).select(permalink=permalink, active=True)
    ultimenews = News().select(batchSize=5, active=True)
    if news:
        mo = news[0]
        mo.clicks = int(mo.clicks or 0)+1
        mo.persist()
        f = "pg/news_detail"
        pageData = {'file' : f,
                    "pg" : 1,
                    "ultimenews":ultimenews,
                    "news":mo}
        return Page(req).render(pageData)
    else:
        pageData = {'file' : 'not_found'}
        return Page(req).render(pageData)



@expose('/pg/ac_main_News/<action>')
@expose('/pg/ac_main_News/')
@expose('/pg/ac_main_News')
def anagraficaMainNews(req, action=None):
    """

    """
    def __show__(req, action=None):
        pageData = {'file' : "/pg/ac_main_News"}
        return Page(req).render(pageData)

    def __list__(req, action=None):
        from dao.NewsCategory import NewsCategory
        from dao.Main_News import MainNews
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_denominazione =  req.form.get("fk_denominazione")
        daos = MainNews().select(
                            #denominazione=fk_denominazione,
                            batchSize=batchSize,
                            offset=offset,
                            orderBy=sorting)
        count = MainNews().count(
                                    #denominazione=fk_denominazione,
                                    batchSize=None)
        #print daos[0].jsanity()

        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)
            }
        #print "QUI", prep2json(daos)
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __edit__(req, action=None):
        from dao.NewsCategory import NewsCategory
        from dao.Main_News import MainNews
        categ = NewsCategory().select(batchSize=None)
        id = req.form.get("id")
        if id:
            d = MainNews().getRecord(id=int(id))
        else:
            d = MainNews()

        pageData = {'file': "pg/addedit/ae_main_news",
                    "dao": d,
                    "categ":categ
                    }
        return Page(req).render(pageData)

    def __create__update__(req, action=None):
        from dao.NewsCategory import NewsCategory
        from dao.Main_News import MainNews
        """Aggiunge una riga alle pesate"""
        idrr = S(req).getUserId()
        id = req.form.get("id")
        if id != "None":
            d = MainNews().getRecord(id=int(id))
        else:
            d = MainNews()
            d.publication_date = datetime.datetime.utcnow()
        try:
            d.id_categoria = int(req.form.get("id_categoria"))
        except:
            d.id_categoria = None
        d.title = str(req.form.get("title"))
        d.abstract = str(req.form.get("abstract"))
        d.body = str(req.form.get("body"))
        d.active = bool(req.form.get("active"))
        d.permalink = permalinkaTitle(req.form.get('title'))

        #if req.form.get('id_language'):
        #languageId = req.form.get('id_language')
        #if languageId != "None":
            #d.id_language = languageId
        #else:
            #d.id_language = 1
        d.persist()
        url_red = "/pg/ac_main_News/"
        return Page(req).redirect(url_red)

    def __delete__(req, action=None):
        from dao.Main_News import MainNews
        """Cancella una riga"""
        id = int(req.form.get("id"))
        d = MainNews().getRecord(id=id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __preview__(req, action=None):
        from dao.Main_News import MainNews
        id = req.form.get("id")
        if not id:
            id = req.args.get("id")
        #salvaInSessione(req, chiave="id_fornitore_selezionato", valore=id)
        d = MainNews().getRecord(id=id)
        try:
            d.clicks = d.clicks +1
        except:
            d.clicks = 1
        pageData = {'file': "/pg/preview",
                    "news": d}
        d.persist()
        return Page(req).render(pageData)


    if action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    elif action == "Preview":
        return __preview__(req, action=action)
    else:
        return __show__(req, action=action)
